﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CarbonExchange.LinqUtilities
{
    public class LazyItem2<TItem>
    {
        public LazyItem2(TItem item)
        {
            _Item = item;
        }

        public LazyItem2(IQueryable<TItem> query)
        {
            _Query = query;
        }

        private IQueryable<TItem> _Query;
        private TItem _Item;

        public bool Loaded
        {
            get
            {
                return _Item != null;
            }
        }

        public TItem Item
        {
            get
            {
                if (_Item == null && _Query != null)
                {
                    _Item = _Query.SingleOrDefault();
                }
                return _Item;
            }
            set
            {
                _Item = value;
                _Query = null;
            }
        }
    }

    public class LazyItem<TItem, TDataItem>
    {
        public LazyItem(TItem item)
        {
            _Item = item;
            itemSet = true;
        }

        public LazyItem(IQueryable<TDataItem> query, Convertion convert)
        {
            _Query = query;
            _Convert = convert;
        }

        private IQueryable<TDataItem> _Query;
        private TItem _Item;
        public TItem Item
        {
            get
            {
                if (!itemSet && _Query != null)
                {
                    _Item = _Convert(_Query.SingleOrDefault());
                    itemSet = true;
                }
                return _Item;
            }
            set
            {
                _Item = value;
                _Query = null;
                itemSet = true;
            }
        }

        private bool itemSet = false;
        public bool Loaded
        {
            get
            {
                return itemSet;
            }
        }

        public delegate TItem Convertion(TDataItem item);
        private Convertion _Convert;


    }
}
